package com.gareve.RainScene.models;

import java.util.LinkedList;
import java.util.List;

import aurelienribon.tweenengine.BaseTween;
import aurelienribon.tweenengine.Timeline;
import aurelienribon.tweenengine.Tween;
import aurelienribon.tweenengine.TweenCallback;
import aurelienribon.tweenengine.TweenManager;
import aurelienribon.tweenengine.equations.Quad;
import aurelienribon.tweenengine.equations.Sine;

import com.badlogic.gdx.math.Rectangle;
import com.gareve.RainScene.views.GameRenderer;

public class GameWorld {
	private final static String TAG = GameWorld.class.getSimpleName();
	
	public Man man;
	public final static int RAINDROP_COUNT = 5;
	public final static int RAINSPLASH_COUNT = 5;
	
	private TweenManager tweenManager = new TweenManager();
	
	public Rectangle dramaticRect,dramaticReveal;
	
	public List<Splash> splashes;
	
	public GameWorld(){
		man = new Man(GameRenderer.GAME_WIDTH / 2f - Man.SIZE_WIDTH/2f, GameRenderer.GAME_HEIGHT * 0.30f);
		
		dramaticRect = new Rectangle(0, 0, 0, 0);
		dramaticReveal = new Rectangle(0, 0, 0, 1f);
		
		Timeline.createSequence()
			.push(Tween.to(dramaticRect, 0, 2f)
					.target(GameRenderer.GAME_HEIGHT * 0.15f)
					.ease(Sine.OUT))
			.push(Tween.to(dramaticReveal, 0, 5f)
					.target(0f)
					.ease(Sine.OUT))
			.setCallback(new TweenCallback() {
				@Override
				public void onEvent(int type, BaseTween<?> source) {
					dramaticReveal = null;
				}
			})
			.start(tweenManager);
		
		splashes = new LinkedList<Splash>();
	}
	
	public void nextStep(float delta){
		man.addAnimationTime(delta);
		while(splashes.size() < RAINSPLASH_COUNT)
			createSplash();
		tweenManager.update(delta);
	}
	
	public RainDrop createRainDrop(){
		float x = (float) (Math.random() * GameRenderer.GAME_WIDTH * 1.3f);
		float y = (float) (Math.random() * GameRenderer.GAME_HEIGHT * 1.5f);

		float dx = RainDrop.SIZE_WIDTH;
		float dy = (float) Math.max(RainDrop.MIN_HEIGHT,RainDrop.MAX_HEIGHT * Math.random());

		x -= GameRenderer.GAME_WIDTH * 0.35f;

		return new RainDrop(x, y, dx, -dy);
	}
	
	private void createSplash(){
		float x = (float) (Math.random() * GameRenderer.GAME_WIDTH);
		float y = GameRenderer.GAME_HEIGHT * 0.15f + (float) (Math.random() * GameRenderer.GAME_HEIGHT * 0.15f);
		
		float startingRadio = 0.5f;
		float targetRadio = 3.0f;
		float splashDuration = (float) (Math.random() / 4f);
		
		Splash splash = new Splash(x, y,startingRadio);
		splashes.add(splash);
		
		Timeline.createSequence()
			.push(Tween.to(splash, 0, splashDuration)
					.target(targetRadio)
					.ease(Quad.INOUT))
			.push(Tween.to(splash,1,0f)
					.target(0f)
					.ease(Quad.IN))
			.start(tweenManager);
	}
}